package com.example.musicserver.controller;


import com.example.musicserver.constant.Constant;
import com.example.musicserver.model.Result;
import com.example.musicserver.model.UserInfo;
import com.example.musicserver.service.UserInfoService;
import com.example.musicserver.tools.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/login")
    public Result<Boolean> login(String username, String password, HttpServletRequest request) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(username);
        userInfo.setPassword(password);
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail(400,"用户名或者密码为空",false);
        }
        UserInfo queryUserInfo = userInfoService.queryByName(username);
        if (queryUserInfo == null) {
            return Result.fail(400,"账号不存在",false);
        }else {
            password = MD5Util.md5(password);
            if (password.equals(queryUserInfo.getPassword())) {
                HttpSession session = request.getSession();
                session.setAttribute(Constant.USERINFO_SESSION_KEY,queryUserInfo);
                session.setAttribute(Constant.USERINFO_SESSION_KEY,userInfo);
                return Result.success(true);
            }else {
                return Result.fail(400,"账号或者密码错误",false);
            }
        }
    }

    @RequestMapping("/registry")
    public Result<Boolean> registry(String regname,String regpassword,String reregpassword) {
        log.info(regname + " " + regpassword + " " + reregpassword);
        if (!StringUtils.hasLength(regname) || !StringUtils.hasLength(regpassword)
                || !StringUtils.hasLength(reregpassword)) {
            return Result.fail(400,"注册失败，用户名或者两次输入的密码为空",false);
        }
        if (!regpassword.equals(reregpassword)) {
            return Result.fail(400,"注册失败，两次输入的密码不一致",false);
        }
        UserInfo userInfo = userInfoService.queryByName(regname);
        if (userInfo != null) {
            return Result.fail(409,"注册失败，该用户已存在",false);
        }else {
            String newPass = MD5Util.md5(regpassword);
            Integer ret = userInfoService.registry(regname,newPass);
            if (ret > 0) {
                return Result.success(true);
            }else {
                return Result.fail(400,"注册失败，请联系管理员",false);
            }
        }
    }
}
